//
//  PhotoBrowserCell.swift
//  HMWeibo
//
//  Created by wulei on 15/12/19.
//  Copyright © 2015年 wulei. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

protocol PhotoBrowserCellDelegate: NSObjectProtocol {
    func PhotoBrowserCellDidTapImage()
}


class PhotoBrowserCell: UICollectionViewCell {
    weak var PhotoDelegate: PhotoBrowserCellDelegate?
    
    // MARK: - 监听方法
    @objc func tapImage() {
PhotoDelegate?.PhotoBrowserCellDidTapImage()
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        print("here")
    }
    var imageURL: NSURL? {
        
        
        
        didSet{
            
            guard let url = imageURL else{
                return
            }
            bmiddleURL(url)
            resetScrollView()



            
            
            // 缩略图
           let placeHolderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString)
            setPlaceHolder(placeHolderImage)

            
//sd_image 有一个功能一旦设置了URL 准备异步加载,清除之前的图片
            //如果之前的图片也是异步加载,但是没有完成会取消之前的异步操作
            // 如果url 对应的图片已经被缓存,直接从磁盘读取,不会再走异步加载
            // 几乎所有的第三方框架,进度回调都是异步的
            // 原因:
            // 1. 不是所有的程序都需要进度回调
            // 2. 进度回调的频率非常高,如果在主线程上,会造成主线程卡顿
            // 3. 使用进度回调,要求界面上跟进进度变化的UI 并不多,而且不会频繁更新
            imageView.sd_setImageWithURL(bmiddleURL(url), placeholderImage: nil, options: [], progress: { (current, total) -> Void in

                
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.placeHolder.progress = CGFloat(current) / CGFloat(total)
                })
                
                }) { (image, _, _, _) -> Void in
                    
                    // 判断图片下载是否成功
                    if image == nil {
                        SVProgressHUD.showInfoWithStatus("你的网络不给力")
                        return
                    }
                    
                    
                    self.placeHolder.hidden = true
                    self.setPosition(image)
            }
        }
    }
    
    
    // 设置占位图像的内容
    private func setPlaceHolder(image: UIImage?) {
        placeHolder.hidden = false
        placeHolder.image = image
        placeHolder.sizeToFit()
        placeHolder.center = scrollView.center
        
    }
    
    
    
    
    // 重设 内容属性
    private func resetScrollView() {
        // 重设 imageView 的内容属性
        imageView.transform = CGAffineTransformIdentity
        
        // 重设 scrollView 的内容属性
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    
    // 设置图片的位置
    private func setPosition(image: UIImage) {
//        self.imageView.center = CGPointZero
        let size = self.displaySize(image)
        // 判断大图
        if displaySize(image).height < scrollView.bounds.height {
            
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            let h = (scrollView.bounds.height - size.height) * 0.5
            let w = (scrollView.bounds.width - size.width) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: h, left: w, bottom: 0, right: 0)

            
        } else {
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            scrollView.contentSize = size
        }
        
        
        

    }
    // 计算等比例缩放之后的图片尺寸
    private func displaySize(image: UIImage) -> CGSize {
        let w = scrollView.bounds.width
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    }
    
    // 拼接中等图片的URL
    private func bmiddleURL(url: NSURL) -> NSURL {
        
        var urlString = url.absoluteString
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        

        return NSURL(string: urlString)!
        
    }
    
    // MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
        // 添加控件
        addSubview(scrollView)
       scrollView.addSubview(imageView)
        scrollView.addSubview(placeHolder)
        
        // 设置约束
        var rect = bounds
        rect.size.width -= 20
        
        scrollView.frame = rect
        
        
        //设置scrollView 的缩放
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        // 添加手势识别
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
    
    
    // 懒加载控件
     lazy var scrollView: UIScrollView = UIScrollView()
     lazy var imageView: UIImageView = UIImageView()
//    private lazy var placeHolder: UIImageView = UIImageView()
    private lazy var placeHolder: ProgressImageView = ProgressImageView()
}

// MARK: - scrollView的代理方法
extension PhotoBrowserCell: UIScrollViewDelegate {
    
    // 返回要缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imageView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        var h = (scrollView.bounds.height - view!.frame.height) * 0.5
        var w = (scrollView.bounds.width - view!.frame.width) * 0.5
        
        h = h < 0 ? 0 : h
        w = w < 0 ? 0 : w
        scrollView.contentInset = UIEdgeInsets(top: h, left: w, bottom: 0, right: 0)
        
        


    }
    
    func scrollViewDidZoom(scrollView: UIScrollView) {

    }
}
